#include <WProgram.h>
#include <avr/io.h> 
#include <avr/interrupt.h> 
#include "ROB_IrRC.h"


volatile uint8_t        IR_remote_with_repeat; // set to 1 in remote_init to analyze repeat commands from IR sender
volatile uint8_t        IR_remote_available; // becomes 1 when a new command is available
volatile uint32_t       IR_remote_data; // stored result: actual command

volatile uint32_t       IR_remote_last_data; // stored result: last command. need this for repeat
volatile unsigned long  IR_remote_last_micros; // micoseconds counter to analyze signal



// Interrupt INT0 for remot control
ISR(INT0_vect)
{
  static uint8_t nr_irqs;

  if(!nr_irqs) { // ignore lead_in and start counting at flank of first bit
    IR_remote_last_micros= micros();
    nr_irqs++;
    return;
  }
  if(nr_irqs==1) { // got first flank after lead_in

    uint8_t lead_in = (int)(micros() - IR_remote_last_micros) >> 11;

    if( 6 ==  lead_in) { // START of bit 0
      IR_remote_last_micros = micros();
      nr_irqs++;
      return;
    }
    else if (IR_remote_with_repeat && 5 == lead_in) { // REPEAT
      IR_remote_available = 1;
      nr_irqs=0;
      IR_remote_data = IR_remote_last_data;
      return;
    }
    else // DIRT
    {
      nr_irqs = 0;
      return;
    }
  }

  //  INT0_IRQ_DISABLE();
  //  INT0_IRQ_CLEAR();
  IR_remote_data <<=1;
  IR_remote_data |= (micros() - IR_remote_last_micros) >> 11;
  IR_remote_last_micros = micros();
  nr_irqs++;

  if(nr_irqs == 34) {
    nr_irqs=0;
    IR_remote_available = 1;
    IR_remote_last_data = IR_remote_data; // prepare for repeat
  }
  //  else {
  //  INT0_IRQ_ENABLE();
  //  }
}






// Init Remote control
void IR_remote_init(uint8_t with_repeat)
{
  IR_remote_data = 0;
  IR_remote_available = 0;
  IR_remote_with_repeat = with_repeat;

  INT0_IRQ_DISABLE();
  INT0_IRQ_CLEAR();
  INT0_FALLING();
  INT0_IRQ_ENABLE();
}


